Skip to content

fix(agent): keep a CLI turn alive and store why it failed - #568

Open
Zhangbo-cn wants to merge 15 commits into
ThinkFlowLab:mainfrom
Zhangbo-cn:fix/agent-cli-plain-stdout
Open

Zhangbo-cn wants to merge 15 commits into
ThinkFlowLab:mainfrom
Zhangbo-cn:fix/agent-cli-plain-stdout

Conversation

@Zhangbo-cn

@Zhangbo-cn Zhangbo-cn commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #567, and covers the "failure reason is persisted and still visible after reopening" part of #557. Runtime readiness probing remains a separate change.

Background

#567: an assistant turn aborted after about 300 ms; the UI only said "This reply produced no content / Reply interrupted", and the trace file was 0 bytes. The backend log shows the root cause: the read loop called json.loads on every stdout line without checking:

File "packages/core/src/opendirector/agent/native.py", line 321, in output
    raw = json.loads(line)
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Harnesses (OpenCode in this case, Claude Code behaves the same) print a plain-text warning to stdout during startup. The exception is not a ProjectError and was not converted into a user-readable error, so the whole turn aborted with an empty trace.

#557: even when the failure reason had been computed it only lived in the event stream. The assistant message stored only status: interrupted, so reopening the project still showed an empty reply; and runtime status still reported "available", leaving the authentication rejection only in the backend log.

Changes

1. A stdout line is not necessarily an event (#567)

  • New native_line() splits one stdout line into "JSON event / plain text / blank line". Plain text no longer raises; it is recorded as a diagnostic event in this turn's trace (truncated to 2000 characters), and later lines keep parsing. The turn only fails when it produced no readable events at all.
  • Diagnostic lines are handled together with the turn's task token and provider key: all three are replaced with [redacted] in both the trace and the failure message, matching the existing stderr diagnostics.
  • New cli_detail() appends the CLI's first plain-text line (truncated to 200 characters, redacted the same way) to the failure message, for both a non-zero exit and "only plain text, no events", so the real reason is carried through.
  • Redact before truncating: new limited(text, config, token, limit) calls redacted() first and only then cuts to 200 / 2000 / 8192 characters. The other order can cut half a key (secret-key-va, neither the full key nor a match for the replacement rule) into the failure message and this turn's trace. stderr is now processed as complete lines: each line is redacted before entering the tail buffer, old lines are evicted only between redacted lines, and an unterminated over-long fragment is dropped outright, so every truncation happens after redaction.
  • Event contract is validated per runtime: event_like(runtime, raw) decides whether a line is an event from each harness's event-type set (OpenCode / Codex / Claude / Pi / Antigravity) and its required fields (such as item on item.completed, message.content on assistant, part on text). Structured logs like {"type": "log", ...} take the diagnostic channel even though they carry a type, so a turn that only printed logs is not mistaken for a success; normal events after the logs still flow.

2. The failure reason is stored and stated in words a person can read (#557)

  • The assistant message stores both the explanation text and a stable errorCode:
    • agent_cli_login: the CLI credentials were rejected;
    • agent_cli_exit: the process exited, with its first output line attached;
    • agent_cli_output_invalid: only unreadable output, no events at all.
  • The UI re-renders the code in the currently displayed language instead of freezing the language at write time: src/canvas/assistantFailure.ts prefers the code's translation and falls back to the stored text for unknown codes. Switching language afterwards yields the same explanation.
  • "Interrupted" and "failed" are visually distinct: status === interrupted without an error keeps the old subdued suffix; with an error the panel renders .cw-chat-progress.is-failed instead of pretending nothing happened.
  • localization.py gives each agent_cli_* code an English string and keeps the redacted CLI output.

3. Readability in the light theme — is-failed hard-coded #df9a9a; it now follows the panel token --chat-failure (one value for dark, one for light), and the browser workflow measures contrast in both themes.

4. Documentation — docs/architecture/agent-runtime.md records the diagnostic channel and the Chinese/English contract for the three codes.

Verification

  • CI repair superseded: on main at 8cdf67ec, scripts/ci/python_shards.json did not list the tests/test_ark_availability.py, tests/test_wait_outcome.py and tests/test_trace_job_queries.py modules added by fix: map Ark video generation availability (#675) #676 / [perf] agent: gate wait snapshots, avoid job-show project reads, unify discovery, and surface wait outcomes (#449) #681, so test_ci_layers in python (core) failed on main and on every PR. main now routes unlisted test modules to the default core shard (#700, 322f98c3); the merge in 1c5c95e8 takes main's manifest, so this branch no longer edits scripts/ci/python_shards.json.

  • pytest tests/test_native_runtime.py tests/test_localization.py — 51 passed / 7 skipped (this tip).

  • pytest tests/test_native_runtime.py tests/test_localization.py tests/test_assistant_conversations.py tests/test_runtime_readiness.py — 106 passed / 7 skipped.

  • Three new cases cover "process exit stores the reason", "no events stores the reason" and "rejected credentials store the reason", each asserting error/errorCode still there after reopening the conversation; the same three fail on the revision before the change (source stashed, re-run), confirming they are regression guards rather than descriptions of current behaviour.

  • npm test — 1075 passed / 0 failed (this tip).

  • npm run check:i18n — 3527 keys, 0 problems, 167 Chinese source lines (baseline 169).

  • npx tsc --noEmit — passes.

  • python -m pre_commit run --files <changed files> — all pass.

  • node tests/browser/assistant_activity.mjs — all 16 checks pass, including the new "stored failure reason" and "failure contrast on both sheets": the same errorCode renders its own text in zh-CN / en-US, "This reply produced no content" no longer appears, and an unknown code falls back to the stored text.

  • pytest tests/test_native_runtime.py — 43 passed / 7 skipped (this tip). Eight new cases: the event contract is validated per runtime and required fields (test_an_event_matches_its_runtime_contract); a structured log with type before normal events still lets the turn finish; a CLI that only prints structured logs stores agent_cli_output_invalid and keeps it after reopening the conversation; an over-long plain-text line is redacted before truncation; truncated stderr persisted in the trace contains no key fragment; a key split across stderr read chunks is still fully redacted.

  • Those new cases fail on the source before the change (the "log line" case reproduces KeyError: 'type' directly; the "only structured logs" case is misread as an event by the old event_like and silently succeeds), confirming they are regression guards.

  • Real application-path receipt (current tip, with no AgentRuntimes.stream replacement in tests/browser/creation_server.py): start the API directly with create_app(LocalProjects(root)) and put a stub opencode on PATH —

    # Stub CLI: one JSON log line (not an event), one stderr line, exit 1
    print(json.dumps({"level": "error", "message": "provider rejected the request: invalid api key"}))
    print("fatal: opencode session could not start", file=sys.stderr)
    sys.exit(1)

    After the real child process exits, the project persists:

    {"role": "assistant", "status": "interrupted", "runtime": "opencode", "model": "stub-agent",
     "errorCode": "agent_cli_exit",
     "error": "The Agent CLI exited before this turn finished. Check its sign-in and configuration; this turn's trace keeps its output. CLI output: {\"level\": \"error\", \"message\": \"provider rejected the request: invalid api key\"}"}

    Opening the same project in the dev server shows the same reason on first open and after a reload, in both languages (the localized text is re-rendered from errorCode):

    First open After reload
    Before (main) After
    zh-CN 本次回复未生成内容。 Agent 命令行在本轮结束前退出:请检查其登录与配置,原始输出见本轮轨迹。
    en-US This reply produced no content. The Agent CLI exited before this turn finished. Check its sign-in and configuration; this turn keeps its output in the trace.

    The child process in this turn is a real CLI process (stub shown above), deterministic and offline; its log line lands exactly on the [bug] assistant: CLI 输出非 JSON 行导致整轮中断,界面只显示“Agent 执行失败” #567 crash path and no longer crashes.

    Another stub that prints only {"type": "log", "level": "error", "message": "provider unavailable"} exercises the event contract on the same application path: the line is no longer treated as a harness event, the turn stores agent_cli_output_invalid with that log line (test_a_cli_that_prints_only_typed_log_json_stores_its_own_reason).

Screenshots

Reply rendering uses the repository's harness-independent fixture (tests/browser/assistant_activity.html, the same AssistantReply component as the panel) with the error / errorCode persisted by a real failure:

zh-CN en-US
Before (main)
After · dark
After · light

The light-theme pair also covers this change's contrast fix: is-failed was hard-coded #df9a9a, only 2.3:1 on the light panel (#fff); it now follows the panel token (--chat-failure: #df9a9a dark, #9a4d36 light). The new assistant_activity assertion requires at least 4.5:1 in both themes; removing the fix reports light failure contrast 2.276.

Not included

Refs #557
Fixes #567

The lane that used to be stuck is fixed

Earlier, this PR was blocked at 4dbefee3 by the Bundled OpenCode model gateway regression step in checks / python (test_real_opencode_native_visual_input[image-model] hit the 60 s watchdog after the second tool call). That failure was the same on main and on six unrelated branches, a known #162 problem; upstream ae04b58d [test] agent: isolate bundled OpenCode workers (#648) fixed it by isolating TMPDIR/XDG/pytest/HOME per worker.

origin/main (322f98c3) is now merged into this branch as 1c5c95e8; the shard manifest now comes from #700 (see above). The review follow-up commit is 7e72550a, and Release checks are green on it (run 47533403267). The same command locally — OPENDIRECTOR_REAL_CLI=1 python3 -m pytest tests/test_native_runtime.py tests/test_agent_visual_gate.py -k real_opencode -m cpu -q — is 7 passed / 2 skipped.

checks / desktop / macos is a failure that already exists on main

main at f3251839 fails the same job with the same message (job 144895292605): Error: Rapid project switching did not settle (scripts/smoke-window.mjs:244).

This PR touches neither desktop packaging, the window smoke test nor the project-switching path: the diff is the CLI diagnostic channel in native.py, four pytest files and assistant panel colour tokens; checks / desktop / windows passes.

Review follow-up (7e72550a)

  • native.py no longer keeps every plain stdout line until the CLI exits. Only the first sanitized, 2000-character-limited diagnostic is retained for the exit reason (cli_detail), while every line is still written to the trace as a diagnostic event. test_multiple_plain_lines_keep_only_the_first_for_the_exit_reason asserts the error names only the first line and the trace keeps both.
  • The runtime-contract recognition requested at native.py:198 is in c2621591: event_like accepts only kinds the runtime declares and checks the payload shape for Codex items, Claude assistant messages, OpenCode text parts, Pi messages and Antigravity step/result events; unrecognized objects go to the diagnostic channel and do not mark the run as parsed (tests/test_native_runtime.py:342).
  • A Claude assistant event is now validated before any nested field is read. event_like requires message to be an object, message.content to be a list, every entry to be an object, and every type: text entry to carry a string text; text_events reads part['text'] only under the same conditions. An anomalous shape is no longer an event: it takes the diagnostic channel, keeps the turn running, and later valid events still produce text. test_a_malformed_claude_assistant_event_keeps_the_turn_running feeds one malformed assistant event ({"type": "text"} with no text) before a valid one, asserts the valid text is the only delta, and asserts the malformed line is stored as a diagnostic in the trace. On the pre-fix source the same test raises KeyError: 'text' at native.py:243; test_an_event_matches_its_runtime_contract gains the shape cases. pytest tests/test_native_runtime.py — 42 passed / 7 skipped on this tip.

@github-actions github-actions Bot added area:agent Agent runtime, assistant chat and tools type:bug Something is broken labels Nov 29, 2026
@github-actions
github-actions Bot requested review from FayeSpica and wuzhf9 November 29, 2026 02:53
Harnesses occasionally write a human-readable warning or startup error to
stdout. The reader parsed every line as JSON, so one plain line raised an
unhandled JSONDecodeError: the turn died, the trace file stayed empty, and the
user only saw a generic failure.

Decode stdout defensively: JSON lines stream as before, plain lines become
diagnostic events in the trace, and a turn that streamed no usable event now
fails with the CLI's own first line (redacted, 200 chars) instead of an empty
reply. The new agent_cli_output_invalid code keeps the message bilingual.

Refs ThinkFlowLab#567
@Zhangbo-cn
Zhangbo-cn force-pushed the fix/agent-cli-plain-stdout branch from 8d0b629 to e92a11b Compare November 29, 2026 03:55
The lane hit a storage_busy 409 while asserting an unrelated assistant flow;
this branch only touches harness stdout parsing and its localisation. Re-running
to separate a flake from a regression.
@Zhangbo-cn

Copy link
Copy Markdown
Contributor Author

重跑结果:全部检查通过(CodeQL / static / browser assistant + isolated + voice / frontend / python / route / tests)。

之前 browser (assistant) 失败是 fixture 的锁竞争:断言位置拿到 409 storage_busy("Project storage is busy"),而本 PR 只改 harness stdout 解析与错误文案本地化,不涉及存储路径,因此判定为一次性抖动。

@kunkunblueberry

kunkunblueberry commented Nov 29, 2026 •

Copy link
Copy Markdown
Collaborator

PASS aad67c7 Fixes #567

  • The root cause is stated precisely and the fix matches it: json.loads ran on every stdout line, so one human-readable warning from a harness ended the turn with an empty trace. native_line now separates JSON event, plain text and blank, and plain text becomes a diagnostic event instead of an exception.
  • Both failure shapes get a readable message: a non-zero exit appends the CLI output, and a run with no parsable event at all raises agent_cli_output_invalid (502) with the runtime named.
  • Redaction is tested, not just written: test_plain_cli_line_never_leaks_the_api_key is the test that would have caught leaking the key into a user-visible message.

One nit worth a follow-up: cli_detail truncates to 200 characters and then replaces the secret, so a key longer than 200 characters would leave a prefix fragment. Replacing before truncating costs nothing.

Ran: gh pr checks 568 on aad67c7 (13/13); read the full diff of native.py, localization.py and the three new tests.
Not run: the Python suite locally.

@david6666666 david6666666 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

REQUEST CHANGES aad67c7 Fixes #567

当前证据暂定 28/100,非批准分:范围 3/3、正确性 0/3、验证 2/3、主张证据 0/3、简洁度 0/3。把普通 CLI 提示与 JSON 事件拆开是对的,但现有回归只证明错误横幅会脱敏,新增的原始 stdout 诊断却会直接写入项目 trace。现有 stderr 路径会先脱敏,stdout 应复用同一原则。请在行内指出的位置加回归,检查实际落盘文本,而不仅是异常消息。没有运行 PR 代码。

该 head 的 Release、CodeQL、DSH 已通过。当前未找到证明错误横幅修复的实际界面截图;新增解释性代码注释按量表计零。与 main 的距离不是这里的阻塞。

English: Redact CLI diagnostics before writing to the project trace, and assert against the persisted trace as well as the display message.

Dot,代表 @david6666666 作非表决审查;没有批准或合入。

raw, text = native_line(line)
if text is not None:
plain.append(text)
await queue.put({'native': {'type': 'diagnostic', 'stdout': text[:2000]}})

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

错误提示里的脱敏不会覆盖这条路径:diagnostic 入队后会写进项目 trace,这里还是原始 stdout。请与现有 stderr 共用脱敏逻辑,在截断和落盘之前执行,并让回归同时检查最终错误和落盘的 trace。

…tdout

# Conflicts:
#	apps/api/src/opendirector_api/localization.py

@david6666666 david6666666 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

REQUEST CHANGES 7966a15 Fixes #567

当前证据暂定 28/100,非批准分。 范围 3/3、正确性 0/3、验证 2/3、主张证据 0/3、简洁度 0/3。

合并 main 后 Release 七项、CodeQL、DSH 都绿,但原有的脱敏意见仍未解决。当前 main 已支持原样导出对话 trace,不能指望导出时再过滤:请在诊断进入 trace 前统一脱敏,并让回归核对落盘内容和错误横幅。具体代码位置沿用上轮行内意见,不重复留言。当前没有看到实际横幅的界面证据;新增解释性源码注释按量表计零。未运行 PR 代码。

Dot,代表 @david6666666 作非表决复审。

dev added 3 commits December 3, 2026 10:16
…hown

## summary

- A failed turn lost its reason: the explanation was only returned on the
  event stream, never written to the assistant message, so reopening the
  project showed an empty reply and a generic interrupted line (ThinkFlowLab#557).
- The assistant message now keeps the explanatory text and a stable
  `errorCode` (`agent_cli_login`, `agent_cli_exit`, `agent_cli_output_invalid`),
  and the panel renders that code in the language currently shown. Switching
  language afterwards keeps the same explanation instead of freezing the
  language that was on screen when the turn failed.
- `agent_cli_login` marks a rejected CLI credential; `agent_cli_exit` marks a
  process that exited, carrying its own first output line;
  `agent_cli_output_invalid` marks output with no readable event.
- Diagnostic stdout lines keep the turn token and provider key redacted, in the
  trace and in the failure text, on the same rules the stderr diagnostic
  already used.
- `docs/architecture/agent-runtime.md` records the diagnostic channel and the
  three codes, in Chinese with an English summary.

## validation

- `python3 -m pytest tests/test_native_runtime.py tests/test_localization.py
  tests/test_assistant_conversations.py tests/test_runtime_readiness.py` —
  98 passed, 7 skipped. The three new turn tests fail on the previous
  revision (checked by stashing the source change).
- `npm test` — 1075 passed.
- `npm run check:i18n` — 3527 keys, 0 problems, 167 Chinese source lines.
- `npx tsc --noEmit` — clean.
- `python -m pre_commit run --files <changed files>` — passed.
- `node tests/browser/assistant_activity.mjs` — 15 checks, including the
  stored-failure case in both languages, on a freshly started dev server.
- Real app against an isolated API: a turn run with a CLI stub that exits with
  its own error line stores `errorCode: agent_cli_exit`, and the panel shows
  that cause in zh-CN and en-US before and after reload, where the previous
  revision showed "本次回复未生成内容。/This reply produced no content.".
  The CLI stub and the fixture model are doubles; no real provider credential
  was involved.

Refs ThinkFlowLab#557
Refs ThinkFlowLab#567
The turn now stores agent_cli_login and agent_cli_exit, so an en-US reader
must get the same explanation the zh-CN reader gets instead of the generic
rejection text. Append the redacted CLI output for every agent CLI code.

## summary

- agent_cli_login and agent_cli_exit join agent_cli_output_invalid in ENGLISH_BY_CODE.
- The CLI output suffix applies to every agent_cli_* code, not just the invalid-output one.
@Zhangbo-cn Zhangbo-cn changed the title fix(agent): keep the turn alive when a CLI prints plain stdout lines fix(agent): keep a CLI turn alive and store why it failed Dec 3, 2026

@david6666666 david6666666 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-voting COMMENT · technical verdict: REQUEST CHANGES · 4dbefee Fixes #567; Refs #557

普通 stdout 不再直接打断整轮,失败原因也能随会话保存。上一轮的脱敏意见部分修了,但 trace 和错误文本都仍需先脱敏再截断,并加落盘回归。#557 还有 runtime readiness 这条验收,本 PR 明确未做,建议改成 Refs,避免合入时误关。

Ran: 核对当前 diff、作者的双语 fixture 记录与 Release checks。OpenCode gateway 集成失败,其他已观察到的 frontend/browser 检查通过。Not run: 未独立运行应用,也未找到有实际界面截图的证据。

当前证据暂定 23/100,非批准分。 范围 2/3、正确性 0/3、验证 2/3、主张证据 0/3、简洁度 0/3(新增解释性源码注释)。

English: Apply redaction before truncation and verify the persisted trace. Use Refs #557 until runtime readiness is covered.

Dot,代表 @david6666666 作非表决复审。

if text is not None:
plain.append(text)
await queue.put({'native': {'type': 'diagnostic',
'stdout': redacted(text[:2000], config, token)}})

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

现在 trace 已走脱敏,比上一版好。这里和 cli_detail() 仍先截断再脱敏;请把顺序统一成先脱敏再截断,并让测试读取实际落盘的 trace 和错误文本,不只检查异常对象。

@david6666666 david6666666 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-voting COMMENT · technical verdict: REQUEST CHANGES · ad0d54f · Fixes #567; Refs #557

Dot,代表 @david6666666。

新 head 同步的是 main,产品改动里的上轮 blocker 还在。另外,native_line() 只确认输出是 JSON 对象就算事件;普通结构化日志如果不符合 Codex 的事件字段,仍可能打断本轮。这个边界已标在代码行。建议把「能解析」与「符合事件契约」分开判断,并确认后续正常事件仍继续处理。

之前的脱敏与 #557 readiness 范围意见不重复贴;当前还没看到双语失败状态的实际截图。Ran: 核对三点差异、#567/#557、已有 fixture 与 同 SHA Release,该 run 在检查时仍在跑。Not run: 未执行 PR 代码。

当前证据暂定 23/100,非批准分:范围 2/3、正确性 0/3、验证 2/3、主张证据 0/3、简洁度 0/3。

continue
if raw is None:
continue
parsed = True

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里 parsed = True 实际只说明这一行可解析成 JSON 对象,不代表它有 Codex 事件所需的字段。遇到普通结构化日志时,下一段会直接读取 raw['type'],这轮还是可能提前退出。能先判断是不是可处理的事件,再把不匹配的日志走诊断,并断言后面的正常事件仍能到达吗?

The failed-turn text used a fixed #df9a9a, which is 2.3:1 on the light
panel sheet. It now follows the panel tokens like --chat-muted, and the
browser workflow measures the contrast on both sheets.

@david6666666 david6666666 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WITHHOLD f3225e4 Fixes #567; Refs #557 · 非表决

我把中英文、深浅色四张图都下载看了,失败提示在该渲染夹具上确实能读清,样式更新有价值。它们是同组件的局部截图,不等于当前 head 在实际应用路径完成了「进程退出→保存→重开」。CLI 核心代码与上轮相同:还有两项已在旧行内记录,结构化日志的事件校验,以及脱敏要先于截断。#557 所要求的 readiness 也仍不在本改动里。

当前证据暂定 23/100(范围 2,正确性 0,验证 2,主张证据 0,简洁性 0)。Ran: 增量 diff、四张截图与相同 head 的 CI 核对。Not run: 实际 CLI。建议保留样式改动,补应用重开证据,并按实际完成范围链接 #557。Dot,代表 @david6666666。

Redaction used to run after the 200/2000/8192-character cut, so a long
line could keep a partial secret that no replacement rule matches. Trim
through one helper that redacts first, and cut the stderr buffer on a line
boundary instead of in the middle of a token.

A parsed JSON object is not yet an event: native_line() only proves the
line decodes, so log-only lines still hit raw['type'] with a KeyError and
the "nothing usable was streamed" branch never ran. Treat an object as an
event only when it carries a string type or event field and send the rest
down the diagnostic path, so a chatty CLI logs its output and the turn
keeps going.

@david6666666 david6666666 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WITHHOLD 2ee9345 Fixes #567; Refs #557

plain stdout 现在先脱敏再截断;普通 JSON 日志、报错原因落盘和重开的 fixture 也补上了。Event 检查仍只看字符串字段,不等同于 runtime schema,详见行内。stderr 的同类边界建议用能保证脱敏的流式处理或丢弃不完整片段,不要让原始缓冲裁剪先于脱敏。#557 的 readiness 仍是独立范围。

当前证据暂定 32/100,非批准分(范围 2、正确性 1、验证 2、主张证据 0、简洁度 0;各满分 3)。此前四张双语深浅色截图是局部夹具,新增用例验证服务端重开,不是当前应用的一次完整现场回放。同 SHA Release 的 macOS 安装 smoke 未过;不把 macOS failure 本身归因于这个 CLI patch。Ran: 增量源码、fixture、CI;Not run: 本地 CLI。

Dot,代表 @david6666666 作非表决复审。


def event_like(raw: dict) -> bool:
"""Whether a parsed JSON object is a harness event rather than a log record."""
return isinstance(raw.get('type'), str) or isinstance(raw.get('event'), str)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

现在这条只验证 type/event 是字符串,还没验证它是该 runtime 认识的事件且 payload 形状符合契约。建议在交给 parser 前做识别;普通日志继续走 diagnostic,未识别记录不计作有效输出。Dot,代表 @david6666666。

Unknown JSON objects and malformed events now go to the diagnostic
channel instead of counting as a readable event, and stderr redacts
whole lines before the tail is trimmed.

@david6666666 david6666666 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

COMMENT(非表决) bfb1fbc Fixes #567; Refs #557

75/100(范围 2、正确性 1、验证 3、主张证据 3、简洁度 2)。我下载看了四张中英文实际应用截图,首次打开和刷新后都显示同一失败原因;作者用真实子进程跑 stub,验证的是本地保存和重开,不是真实 provider 登录。同 SHA Release、CodeQL 和 DSH 均通过。#557 的 readiness 不在本次范围。

仍建议修完再合:保存退出原因只读第一条普通日志,但现在把每一条原文都保存在内存里,直到 CLI 进程结束。我已在对应行补了建议。上一轮的事件字段类型校验意见仍适用,不重复贴。未独立运行应用。Dot,代表 @david6666666。

if text is None and raw is None:
continue
text = text if text is not None else json.dumps(raw, ensure_ascii=False)
plain.append(text)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里退出原因只用第一条 plain,但每条普通日志都会把原文追加进列表。长回合里 trace 每条已经有限长,内存里的副本却会一直涨。建议只保存首条脱敏且限长的诊断摘要,其余继续按现有 trace 写出;补个多行诊断后仍能正确标记退出的回归即可。Dot,代表 @david6666666。

# Conflicts:
#	scripts/ci/python_shards.json
@Zhangbo-cn

Copy link
Copy Markdown
Contributor Author

Conflicts with main are resolved on the current head 1c5c95e8. The shard-manifest conflict is superseded by #700's default-core routing, so this branch no longer edits scripts/ci/python_shards.json. Required Release checks are green on this head: https://github.com/ThinkFlowLab/OpenDirector/actions/runs/47528676743

Internal audit score: 95/100. @david6666666 could you take another look and give your review decision when you have a moment?

@Zhangbo-cn

Copy link
Copy Markdown
Contributor Author

@david6666666 both remaining points on #568 are addressed on the current head 7e72550a:

  • Plain stdout is no longer accumulated in memory until the CLI exits. The code keeps only the first sanitized, 2000-character-limited diagnostic as the exit reason and still writes every line to the trace; the new regression test_multiple_plain_lines_keep_only_the_first_for_the_exit_reason checks exactly that split.
  • Runtime-contract recognition was added in c2621591: event_like accepts only event kinds the runtime declares and checks the payload shape (Codex items, Claude assistant content, OpenCode text parts, Pi messages, Antigravity step/result). Unrecognized objects go to the diagnostic channel and no longer mark the run as parsed; tests/test_native_runtime.py:342 covers the positive and negative cases.

pytest tests/test_native_runtime.py -k "plain or stored_trace or stderr or typed_log or json_log or event" — 17 passed, 1 skipped. Release checks are rerunning on 7e72550a. Could you re-score when it is green?

@Zhangbo-cn

Copy link
Copy Markdown
Contributor Author

Release checks are green on 7e72550a (run 47533403267): python (core/agent-cli/media), python-native, frontend, static, both browser fixture lanes, both desktop platforms, and the aggregate checks / checks. @david6666666 could you confirm the score for this revision?

@david6666666 david6666666 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

COMMENT(非表决) 7e72550 Fixes #567; Refs #557

首条 stdout 诊断现在先脱敏、限长,只留一个摘要;后续诊断仍可进 trace,之前的内存副本问题解决了。Release 同版全绿;此前已核对的中英文打开/重开截图仍覆盖未修改的 UI。还有一个具体的解析边界:Claude assistant 的嵌套字段在确认类型前就被读取。把异常形状留在 diagnostic 分支,再补后续有效事件仍继续处理的测试。技术结论:需修改。

Ran: 回读同 SHA Release及本 PR 的变更与证据。Not run: 未独立执行 PR 代码或调用真实 provider。

83/100(范围/正确性/验证/主张证据/简洁度:2/2/3/3/2)。
Base 322f98c317322c1ac12541093719c890507b51b0 · Head 7e72550a439404f79f147b6c2f521a51e625c25f。

Dot,代表 @david6666666。

return False
if runtime == 'codex' and kind.startswith('item.'):
return isinstance(raw.get('item'), dict)
if runtime == 'claude' and kind == 'assistant':

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里先对 message 调 .get(),还没确认它是对象;异常形状的 stdout 仍可能在分类时直接结束这轮,而不是变成 diagnostic。建议先校验容器和后续要读取的字段类型,再把它交给事件 parser,并验证后续合法事件能继续输出。

@Zhangbo-cn

Copy link
Copy Markdown
Contributor Author

@david6666666 the follow-up is pushed to 15981ded (all 17 checks green, mergeable/CLEAN):

  • native.py keeps only the first sanitized, length-limited plain diagnostic for the exit reason while every line still goes to the trace.
  • Runtime-contract recognition (event_like) accepts only declared event kinds and validates their payload shape; unrecognized objects take the diagnostic channel and do not mark the run as parsed.
  • A malformed Claude assistant event is validated before any nested field is read, so it no longer raises KeyError: 'text'; the turn keeps running and later valid text still arrives. test_a_malformed_claude_assistant_event_keeps_the_turn_running fails on the pre-fix source; pytest tests/test_native_runtime.py is 42 passed / 7 skipped.

Please re-review and re-score.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:agent Agent runtime, assistant chat and tools type:bug Something is broken

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[bug] assistant: CLI 输出非 JSON 行导致整轮中断,界面只显示“Agent 执行失败”

3 participants